package com.sk.cardeal.act.home.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.widget.AppCompatSeekBar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.luck.picture.lib.entity.LocalMedia;
import com.sk.cardeal.R;
import com.sk.cardeal.app.MyApplication;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.callback.HandleDataCallBack;
import com.sk.cardeal.common.Constants;
import com.sk.cardeal.entity.CustomDetails;
import com.sk.cardeal.entity.FixType;
import com.sk.cardeal.entity.FixTypeList;
import com.sk.cardeal.entity.OcrInfo;
import com.sk.cardeal.entity.SaveGetCarBean;
import com.sk.cardeal.entity.WorkFormDetails;
import com.sk.cardeal.utils.AppApi;
import com.sk.cardeal.utils.FileUtil;
import com.sk.cardeal.utils.MyApplicationLike;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.utils.RecognizeService;
import com.sk.cardeal.utils.SnackUtils;
import com.sk.cardeal.view.LineMenuView;
import com.sk.cardeal.view.TitleView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.sk.cardeal.common.Constants.CAR_CARD;
import static com.sk.cardeal.common.Constants.CHOOSE_TYPE;

/**
 * Created by sk on 2017/12/14.
 */

public class GetCarActivity extends BaseActivity implements HandleDataCallBack, SeekBar.OnSeekBarChangeListener {

    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.scan)
    ImageView scan;
    @BindView(R.id.car_num)
    EditText carNum;
    @BindView(R.id.danwei)
    TextView danwei;
    @BindView(R.id.km_num)
    EditText kmNum;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.f)
    TextView f;
    @BindView(R.id.seek_bar)
    AppCompatSeekBar seekBar;
    @BindView(R.id.e)
    TextView e;
    @BindView(R.id.appearance)
    LineMenuView appearance;
    @BindView(R.id.ornaments)
    LineMenuView ornaments;
    @BindView(R.id.fix_type)
    LineMenuView fixType;
    @BindView(R.id.clean_type)
    LineMenuView cleanType;
    @BindView(R.id.handle_parts)
    LineMenuView handleParts;
    @BindView(R.id.ed_remark)
    EditText edRemark;
    @BindView(R.id.save)
    TextView save;
    @BindView(R.id.get_car)
    TextView getCar;
    @BindView(R.id.ed_phone)
    EditText edPhone;
    @BindView(R.id.in_date)
    LineMenuView inDate;

    private List<LocalMedia> appearList = new ArrayList<>();
    private List<LocalMedia> ornamantsList = new ArrayList<>();

    private String appearUrl = "";
    private String ornamentUrl = "";

    private int percent = 0;

    SaveGetCarBean saveGetCarBean;

    private static final int APPEAR = 1;

    private static final int ORNAMENT = 2;

    private String carTypeUrl = "";

    private int cleanTypeParamrs;
    private LoadingDialog loadingDialog;

    private int isUpdate = 0;

    private String orderId = "";

    private String brandUrl = "";


    @Override
    protected int getContentView() {
        return R.layout.activity_get_car;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);

        isUpdate = getIntent().getIntExtra("isUpdate", 0);

        saveGetCarBean = new SaveGetCarBean();


        if (isUpdate == 1) {
            loadingDialog.show();
            orderId = getIntent().getStringExtra("orderId");
            saveGetCarBean.setId(orderId);
            AppApi.workFormDetails(orderId, this, 200, this);
        } else {
            saveGetCarBean.setCode(MyUtils.getRndNumCode());
        }

        saveGetCarBean.setType("2");
        titleView.setMyCallBack(this);
        seekBar.setOnSeekBarChangeListener(this);

        carNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 7) {
                    if (MyUtils.isCarNumber(s.toString())) {
                        AppApi.customDetails(s.toString(), GetCarActivity.this, 300, GetCarActivity.this);
                    } else {
                        SnackUtils.showError(mRootView, "您输入的车牌号，不合法！");
                    }
                }
            }
        });

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");// HH:mm:ss
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        saveGetCarBean.setInTime(simpleDateFormat.format(date));
        inDate.setHint(simpleDateFormat.format(date));
        inDate.setHintColor(Color.parseColor("#232323"));

        handleParts.setHint("不回收");
        handleParts.setHintColor(Color.parseColor("#232323"));
        saveGetCarBean.setPartProcess("0");

        cleanType.setHint("清洗");
        cleanType.setHintColor(Color.parseColor("#232323"));
        saveGetCarBean.setCleanType("1");
    }

    @Override
    public void clickTitle(int i) {
        super.clickTitle(i);
        switch (i) {
            case 1:
                finish();
                break;
        }
    }

    @OnClick({R.id.scan, R.id.appearance, R.id.ornaments, R.id.fix_type, R.id.clean_type, R.id.handle_parts, R.id.save, R.id.get_car, R.id.in_date})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.scan:
                if (MyApplicationLike.isHasGotToken()) {
                    Intent scanIntent = new Intent(mContext, CameraActivity.class);
                    scanIntent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                            FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                    scanIntent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                            CameraActivity.CONTENT_TYPE_BANK_CARD);
                    startActivityForResult(scanIntent, CAR_CARD);
                } else {
                    SnackUtils.showError(mRootView, "ocr扫描尚未准备就绪！");
                }
                break;
            case R.id.appearance:
                Intent appearanceIntent = new Intent(mContext, UpLoadPictureActivity.class);
                appearanceIntent.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) appearList);
                appearanceIntent.putExtra("url", appearUrl);
                appearanceIntent.putExtra("carNum", carNum.getText().toString());
                appearanceIntent.putExtra("brandUrl",brandUrl);
                startActivityForResult(appearanceIntent, APPEAR);
                break;
            case R.id.ornaments:
                Intent ornamantsIntent = new Intent(mContext, UpLoadPictureActivity.class);
                ornamantsIntent.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) ornamantsList);
                ornamantsIntent.putExtra("url", ornamentUrl);
                ornamantsIntent.putExtra("carNum", carNum.getText().toString());
                ornamantsIntent.putExtra("brandUrl",brandUrl);
                startActivityForResult(ornamantsIntent, ORNAMENT);
                break;
            case R.id.fix_type:
                loadingDialog.show();
                AppApi.getFixType(GetCarActivity.this, 7, GetCarActivity.this);
                break;
            case R.id.clean_type:
                Intent cleanIntent = new Intent(mContext, ChooseActivity.class);
                cleanIntent.putExtra("type", Constants.IS_CLEAN);
                startActivityForResult(cleanIntent, Constants.CHOOSE_IS_CLEAN);
                break;
            case R.id.handle_parts:
                Intent hanldeIntent = new Intent(mContext, ChooseActivity.class);
                hanldeIntent.putExtra("type", Constants.IS_HANDLE);
                startActivityForResult(hanldeIntent, Constants.CHOOSE_IS_HANDLE);
                break;
            case R.id.save:


                if (!MyUtils.isCarNumber(carNum.getText().toString())) {
                    SnackUtils.showError(mRootView, "您输入的车牌号不合法！");
                    return;
                }

                saveGetCarBean.setCarNumber(carNum.getText().toString());
                saveGetCarBean.setMileage(kmNum.getText().toString());
                saveGetCarBean.setAppearancePic(appearUrl);
                saveGetCarBean.setInteriorPic(ornamentUrl);
                saveGetCarBean.setCompanyId(MyUtils.getUser(mContext).getCompanyId());
                saveGetCarBean.setNote(edRemark.getText().toString());
                saveGetCarBean.setFuelPercent(tvNum.getText().toString());
                saveGetCarBean.setPhone(edPhone.getText().toString());
                saveGetCarBean.setState("8");
                loadingDialog.show();
                AppApi.saveGetCar(saveGetCarBean, GetCarActivity.this, 1, GetCarActivity.this);
                break;
            case R.id.get_car:

                if (TextUtils.isEmpty(carNum.getText().toString())) {
                    SnackUtils.showError(mRootView, "请输入您的车牌号！");
                    return;
                }

                if (!MyUtils.isCarNumber(carNum.getText().toString())) {
                    SnackUtils.showError(mRootView, "您输入的车牌号不合法！");
                    return;
                }

                if (TextUtils.isEmpty(edPhone.getText().toString())) {
                    SnackUtils.showError(mRootView, "请输入联系号码！");
                    return;
                }

                saveGetCarBean.setCarNumber(carNum.getText().toString());
                saveGetCarBean.setAppearancePic(appearUrl);
                saveGetCarBean.setMileage(kmNum.getText().toString());
                saveGetCarBean.setInteriorPic(ornamentUrl);
                saveGetCarBean.setCompanyId(MyUtils.getUser(mContext).getCompanyId());
                saveGetCarBean.setNote(edRemark.getText().toString());
                saveGetCarBean.setFuelPercent(tvNum.getText().toString());
                saveGetCarBean.setPhone(edPhone.getText().toString());
                saveGetCarBean.setState("0");
                loadingDialog.show();
                AppApi.saveGetCar(saveGetCarBean, GetCarActivity.this, 2, GetCarActivity.this);
                break;
            case R.id.in_date:

                DatePickDialog dialog = new DatePickDialog(this);
                //设置上下年分限制
                dialog.setYearLimt(5);
                //设置标题
                dialog.setTitle("选择进场日期");
                //设置类型
                dialog.setType(DateType.TYPE_ALL);
                //设置消息体的显示格式，日期格式
                dialog.setMessageFormat("yyyy-MM-dd HH:mm");
                //设置选择回调
                dialog.setOnChangeLisener(null);
                //设置点击确定按钮回调
                dialog.setOnSureLisener(new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        inDate.setHint(MyUtils.stampToDate(date.getTime()));
                        saveGetCarBean.setInTime(MyUtils.stampToDate(date.getTime()));
                        inDate.setHintColor(Color.parseColor("#232323"));
                    }
                });
                dialog.show();

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case APPEAR:
                    Log.v("success", data.getStringExtra("url"));
                    appearUrl = data.getStringExtra("url");
                    List<LocalMedia> localMediaList = data.getParcelableArrayListExtra("list");
                    if (appearUrl != null && appearUrl.length() > 0) {
                        appearance.setHintColor(Color.parseColor("#232323"));
                        appearance.setHint("已拍照");
                        appearList.clear();
                        appearList.addAll(localMediaList);
                    }
                    break;
                case ORNAMENT:
                    Log.v("success", data.getStringExtra("url"));
                    ornamentUrl = data.getStringExtra("url");
                    List<LocalMedia> localMediaArrayList = data.getParcelableArrayListExtra("list");
                    if (ornamentUrl != null && ornamentUrl.length() > 0) {
                        ornaments.setHintColor(Color.parseColor("#232323"));
                        ornaments.setHint("已拍照");
                        ornamantsList.clear();
                        ornamantsList.addAll(localMediaArrayList);
                    }
                    break;
                case Constants.CHOOSE_IS_CLEAN:
                    String isClean = data.getStringExtra("data");
                    if (isClean.equals("清洗")) {
                        saveGetCarBean.setCleanType("1");
                    } else if (isClean.equals("不清洗")) {
                        saveGetCarBean.setCleanType("0");
                    }
                    cleanType.setHint(isClean);
                    cleanType.setHintColor(Color.parseColor("#232323"));
                    break;
                case Constants.CHOOSE_IS_HANDLE:
                    String isHandel = data.getStringExtra("data");
                    if (isHandel.equals("回收")) {
                        saveGetCarBean.setPartProcess("1");
                    } else if (isHandel.equals("不回收")) {
                        saveGetCarBean.setPartProcess("0");
                    }
                    handleParts.setHint(isHandel);
                    handleParts.setHintColor(Color.parseColor("#232323"));
                    break;
                case CHOOSE_TYPE:
                    FixType selectType = data.getParcelableExtra("data");
                    fixType.setHint(selectType.getName());
                    saveGetCarBean.setRepairType(selectType.getId());
                    fixType.setHintColor(Color.parseColor("#232323"));
                    break;
                case CAR_CARD:
                    RecognizeService.recLicensePlate(FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath(),
                            new RecognizeService.ServiceListener() {
                                @Override
                                public void onResult(String result, Bitmap bitmap) {
                                    Log.v("recLicensePlate", result);
                                    if (bitmap != null) {
                                        OcrInfo ocrInfo = JSONObject.parseObject(result, OcrInfo.class);
                                        carNum.setText(ocrInfo.getWords_result().getNumber());
                                    } else {
                                        SnackUtils.showError(mRootView, "识别失败，请重试!");
                                    }
                                }
                            });

                    break;
            }
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 1:
                Toast.makeText(mContext, "保存成功！", Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
                finish();
                break;
            case 2:
                Toast.makeText(mContext, "接车工单提交成功！！", Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
                finish();
                break;
            case 7:
                FixTypeList fixTypeList = JSON.parseObject(result, FixTypeList.class);
                ArrayList<FixType> fixTypes = (ArrayList<FixType>) fixTypeList.getResultList();
                Intent intent = new Intent(mContext, FixTypeActivity.class);
                intent.putExtra("data", fixTypes);
                startActivityForResult(intent, CHOOSE_TYPE);
                break;
            case 200:

                WorkFormDetails workFormDetails = JSON.parseObject(result, WorkFormDetails.class);

                saveGetCarBean.setCode(workFormDetails.getReturnObject().getCode());

                carNum.setText(workFormDetails.getReturnObject().getCarNumber());
                edPhone.setText(workFormDetails.getReturnObject().getPhone());
                kmNum.setText(workFormDetails.getReturnObject().getMileage());
                edRemark.setText(workFormDetails.getReturnObject().getNote());

                seekBar.setProgress(Integer.parseInt(workFormDetails.getReturnObject().getFuelPercent()));
                saveGetCarBean.setPartProcess(workFormDetails.getReturnObject().getFuelPercent());


                fixType.setHint(workFormDetails.getReturnObject().getRepairName());
                saveGetCarBean.setRepairType(workFormDetails.getReturnObject().getRepairType());
                fixType.setHintColor(Color.parseColor("#232323"));

                if (workFormDetails.getReturnObject().getPartProcess() == 1) {
                    handleParts.setHint("回收");
                    handleParts.setHintColor(Color.parseColor("#232323"));
                    saveGetCarBean.setPartProcess("1");
                } else if (workFormDetails.getReturnObject().getPartProcess() == 0) {
                    handleParts.setHint("不回收");
                    handleParts.setHintColor(Color.parseColor("#232323"));
                    saveGetCarBean.setPartProcess("0");
                }

                if (workFormDetails.getReturnObject().getCleanType() == 1) {
                    cleanType.setHint("清洗");
                    cleanType.setHintColor(Color.parseColor("#232323"));
                    saveGetCarBean.setCleanType("1");
                } else if (workFormDetails.getReturnObject().getCleanType() == 0) {
                    cleanType.setHint("不清洗");
                    cleanType.setHintColor(Color.parseColor("#232323"));
                    saveGetCarBean.setCleanType("0");
                }


                appearUrl = workFormDetails.getReturnObject().getAppearancePic();
                saveGetCarBean.setAppearancePic(appearUrl);
                if (appearUrl != null && appearUrl.length() > 0) {
                    appearance.setHintColor(Color.parseColor("#232323"));
                    appearance.setHint("已拍照");
                }

                ornamentUrl = workFormDetails.getReturnObject().getInteriorPic();
                saveGetCarBean.setInteriorPic(ornamentUrl);
                if (ornamentUrl != null && ornamentUrl.length() > 0) {
                    ornaments.setHintColor(Color.parseColor("#232323"));
                    ornaments.setHint("已拍照");
                }
                break;
            case 300:

                CustomDetails customDetails = JSON.parseObject(result, CustomDetails.class);
                if (TextUtils.isEmpty(edPhone.getText().toString())) {
                    edPhone.setText(customDetails.getReturnObject().getTelephone());
                }
                if (TextUtils.isEmpty(customDetails.getReturnObject().getBaseCustomerCar().getPath())){
                    brandUrl = customDetails.getReturnObject().getBaseCustomerCar().getPath();
                }

                if(customDetails.getReturnObject().getBaseConvention()!=null){
                    fixType.setHint(customDetails.getReturnObject().getBaseConvention().getTypeName());
                    saveGetCarBean.setRepairType(customDetails.getReturnObject().getBaseConvention().getConventionTypeId());
                }

                break;
        }
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        tvNum.setText(String.valueOf(progress));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}
